package com.appleyk.plan;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.FixedRateTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>越努力，越幸运</p>
 * 计划执行
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @date created on  11:12 下午 2020/12/23
 */
@Service
public class PlanPerformService implements InitializingBean, SchedulingConfigurer {

    @Autowired
    private ScheduledThreadPoolExecutor scheduledExecutor;

    private ScheduledTaskRegistrar scheduledTaskRegistrar;

    private final AtomicInteger planCount = new AtomicInteger(0);

    @Override
    public void afterPropertiesSet() throws Exception {
        // 重新设置定时线程池的线程工厂，指定线程名称（当然，不同的线程池应该另起炉灶而不是用一个）
        scheduledExecutor.setThreadFactory(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"plan-"+planCount.incrementAndGet());
            }
        });
        System.out.println("配置成功");
    }

    // 必须开启了@EnableScheduling注解才会进到下面这个方法
    @Override
    public void configureTasks(@Nullable ScheduledTaskRegistrar scheduledTaskRegistrar) {
        Assert.notNull(scheduledTaskRegistrar, "registrar cannot be null.");
        Assert.notNull(scheduledExecutor, "Scheduler cannot be null.");
        this.scheduledTaskRegistrar = scheduledTaskRegistrar;
        this.scheduledTaskRegistrar.setScheduler(scheduledExecutor);
    }

    public void executeByCron(Runnable task ,String triggerValue){
        this.scheduledTaskRegistrar.scheduleCronTask(new CronTask(task,triggerValue));
    }

    public void executeByFixedRate(Runnable task ,long interval){
        // 每到interval毫秒后，延迟0s执行任务，将上一个任务开始执行时间作为起点
        this.scheduledTaskRegistrar.scheduleFixedRateTask(new FixedRateTask(
                task,interval,0));
    }
}
